package com.example.inspurfabricapp.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.StringUtils;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.ContractEvent;

import javax.annotation.Resource;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.function.Consumer;

/**
 * @author lijiahao
 * @date 2024/7/4
 */
@Slf4j
public class ChaincodeEventListener implements Runnable {

    final Contract contract;

    public ChaincodeEventListener(Contract contract) {
        this.contract = contract;

        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                thread.setName(this.getClass().getSimpleName() + "chaincode_event_listener");
                return thread;
            }
        });
        executor.execute(this);
    }

    @Override
    public void run() {
        log.info("Fabric合约事件正在监听");
        contract.addContractListener(new Consumer<ContractEvent>() {
            @Override
            public void accept(ContractEvent event) {
                log.info("监听到合约事件 -> eventName:{},chaincodeId:{},payload {} ", event.getName(), event.getChaincodeId(), event.getPayload().isPresent() ? StringUtils.newStringUtf8(event.getPayload().get()) : null);
            }
        }, "createWmsEvent");
    }
}
